package auth

import (
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

// 认证码从环境变量获取
const authCodeEnvKey = "UPLOAD_AUTH_CODE"

type AuthResult struct {
	Success    bool
	StatusCode int
	Message    string
}

func ValidateAuthCode(c *gin.Context, authCodeParam string) AuthResult {
	// 优先使用命令行参数指定的认证码
	authCode := authCodeParam
	if authCode == "" {
		// 若命令行参数未指定，从环境变量获取认证码
		authCode = os.Getenv(authCodeEnvKey)
		if authCode == "" {
			return AuthResult{
				Success:    false,
				StatusCode: http.StatusInternalServerError,
				Message:    "服务器配置错误，未设置认证码",
			}
		}
	}

	// 获取请求中的认证码
	if c.ContentType() == "application/json" {
		var request struct {
			Code string `json:"code"`
		}
		if err := c.ShouldBindJSON(&request); err != nil {
			return AuthResult{
				Success:    false,
				StatusCode: http.StatusBadRequest,
				Message:    "请求格式错误",
			}
		}
		if request.Code != authCode {
			return AuthResult{
				Success:    false,
				StatusCode: http.StatusUnauthorized,
				Message:    "认证码错误",
			}
		}
	} else {
		code := c.PostForm("code")
		if code != authCode {
			return AuthResult{
				Success:    false,
				StatusCode: http.StatusUnauthorized,
				Message:    "认证码错误，禁止操作",
			}
		}
	}

	return AuthResult{
		Success:    true,
		StatusCode: http.StatusOK,
		Message:    "认证成功",
	}
}
